package com.haoxin.ai_course.modules.controller;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.haoxin.ai_course.common.base.AbstractController;
import com.haoxin.ai_course.common.utils.HttpGetRequest;
import com.haoxin.ai_course.common.utils.R;
import com.haoxin.ai_course.common.utils.WeixinCheckoutUtil;
import com.haoxin.ai_course.modules.sys.service.H5StatisticsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;



/**
 * 字典数据表
 * 
 * @author xingxiangguo
 * @email bugcn@qq.com
 * @date 2022-03-25 11:30:40
 */
@RestController
@AllArgsConstructor
@Api(value="api",tags="数据统计")
@RequestMapping("/officialAccount")
@Slf4j
public class CheckSinnatureController  extends AbstractController {
	final H5StatisticsService h5StatisticsService;
//	 public static final String APP_ID = "wxf655448f0a9caa2e";
//	 public static final String APP_SECRET = "29d14983b3445403c5977e48d85251c5";
	 public static final String APP_ID = "wx8e84bebfa42f9db0";
	 public static final String APP_SECRET = "8ae0a6e6038874ac299f564295f2cb5e";
	 
	    public static final String GET_ACCESS_TOKEN = "get_access_token";
	 
	    public static final String GET_JSAPI_TICKET = "get_jsApi_Ticket";
	 
	    //长期缓存
	    public static Integer INDEX_COUNT_EXPIRE_TIME = 2 * 60 * 60;
	 
	 
	    /**
	     * 用于微信服务器配置回调我们的接口
	     *
	     * @return
	     */
	    @GetMapping("/checkSignature")
	    public String test(String signature,String timestamp,String nonce,String echostr) {
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
	        if (signature != null && WeixinCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
	            return echostr;
	        }
	        return null;
	    }
	 
	 
	    @ApiOperation(value = "微信公众号获取JS签名", notes = "微信公众号获取JS签名", httpMethod = "GET")
	    @GetMapping("/getSignature")
	    public R getWXSign(String url) throws Exception {
	        Map<String, String> ret = new HashMap<String, String>();
	        String accessToken = getAccessToken();
	        String jsapi_ticket = getTicket(accessToken);
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";
	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                "&noncestr=" + nonce_str +
	                "&timestamp=" + timestamp
	                +"&url=" + url;
	        try {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	            ret.put("url", url);
	            ret.put("jsapi_ticket", jsapi_ticket);
	            ret.put("nonceStr", nonce_str);
	            ret.put("appId", APP_ID);
	            ret.put("timestamp", timestamp);
	            ret.put("signature", signature);
	            return R.ok().put("data",ret);
	        } catch (Exception e) {
	            ret.put("exception", e.getMessage());
	            return R.ok().put("data",ret);
	        }
	 
	    }
	 
	 
	    /**
	     * 获取accessToken
	     *
	     * @return
	     */
	    public String getAccessToken() throws Exception {
	        //获取redis存储
	        String access_token =null;
	        String json = HttpGetRequest.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
	                + APP_ID
	                + "&secret=" + APP_SECRET);
	        JSONObject jsonObject = (JSONObject) JSONObject.parse(json);
	        access_token = jsonObject.get("access_token").toString();
	        //redis缓存
	        return access_token;
	    }
	 
	    /**
	     * 根据accessToken获取jsticket
	     *
	     * @param accessToken
	     * @return
	     * @throws Exception
	     */
	    public String getTicket(String accessToken) throws Exception {
	        //获取redis存储
	        String ticket = null;
	        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
	        JsonObject jsApiTicket = null;
	        try {
	        	String result = HttpGetRequest.doGet(url);
//	        	{"errcode":0,"errmsg":"ok","ticket":"O3SMpm8bG7kJnF36aXbe8_EK1_lWAdzDN3yzKHfETMaHkIjfoKme8jWlmh6NgFpK99Buaysv_CuzkOEMedpDnQ","expires_in":7200}
				System.out.println("微信服务器获取Ticket:"+result);
				JSONObject rqJsonObject = JSONObject.parseObject(result);
	            jsApiTicket = JSONObject.toJavaObject(rqJsonObject, JsonObject.class);
	            ticket = rqJsonObject.getString("ticket");
	            return ticket;
	        } catch (Exception ex) {
	        }
	        return " ";
	    }
	 
	    /**
	     * ------------------------------------------------微信获取jsapi_ticket  DEMO-------------------------------------------------------------------
	     */
	 
	 
	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash) {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }
	 
	    private static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }
	 
	    private static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
}
